package zhengyanze.com.aipoemmax.guide.utils;

import android.content.Context;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;

import zhengyanze.com.aipoemmax.guide.bean.PoemBean;

/**
 * 本地文件管理工具
 * Created by zheng on 2017/8/16.
 */

public class LocationUtils {

    private static final String FILE_PATH ="locationPoem.txt";

    static LocationUtils mLocationUtils;
    static Context mContext;

    public static LocationUtils getLocation(Context context) {
        mContext = context;
        if (mLocationUtils == null) {
            mLocationUtils = new LocationUtils();
        }
        return mLocationUtils;
    }

    /**
     * 保存文件到本地
     */
    public void saveFile(Object object) {
        File file = new File(mContext.getFilesDir(),FILE_PATH);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //使用对象流
        try {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
            oos.writeObject(object);
            oos.flush();
            oos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public ArrayList getFile() {
        File file = new File(mContext.getFilesDir(), FILE_PATH);
        if (!file.exists()) {
            return null;
        }
        ArrayList<Object> objects = new ArrayList();
        try {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
            Object object = ois.readObject();
            objects = (ArrayList<Object>) object;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return objects;
    }
}
